"use strict";
var t = require("../../chunks/three-platformize.js"),
  e = require("../../chunks/OrbitControls.js");
const s = /^[og]\s*(.+)?/,
  i = /^mtllib /,
  r = /^usemtl /,
  o = /^usemap /,
  n = new t.Vector3,
  a = new t.Vector3,
  l = new t.Vector3,
  c = new t.Vector3,
  h = new t.Vector3;

function p() {
  const t = {
    objects: [],
    object: {},
    vertices: [],
    normals: [],
    colors: [],
    uvs: [],
    materials: {},
    materialLibraries: [],
    startObject: function (t, e) {
      if (this.object && !1 === this.object.fromDeclaration) return this.object.name = t, void(this.object.fromDeclaration = !1 !== e);
      const s = this.object && "function" == typeof this.object.currentMaterial ? this.object.currentMaterial() : void 0;
      if (this.object && "function" == typeof this.object._finalize && this.object._finalize(!0), this.object = {
          name: t || "",
          fromDeclaration: !1 !== e,
          geometry: {
            vertices: [],
            normals: [],
            colors: [],
            uvs: [],
            hasUVIndices: !1
          },
          materials: [],
          smooth: !0,
          startMaterial: function (t, e) {
            const s = this._finalize(!1);
            s && (s.inherited || s.groupCount <= 0) && this.materials.splice(s.index, 1);
            const i = {
              index: this.materials.length,
              name: t || "",
              mtllib: Array.isArray(e) && e.length > 0 ? e[e.length - 1] : "",
              smooth: void 0 !== s ? s.smooth : this.smooth,
              groupStart: void 0 !== s ? s.groupEnd : 0,
              groupEnd: -1,
              groupCount: -1,
              inherited: !1,
              clone: function (t) {
                const e = {
                  index: "number" == typeof t ? t : this.index,
                  name: this.name,
                  mtllib: this.mtllib,
                  smooth: this.smooth,
                  groupStart: 0,
                  groupEnd: -1,
                  groupCount: -1,
                  inherited: !1
                };
                return e.clone = this.clone.bind(e), e
              }
            };
            return this.materials.push(i), i
          },
          currentMaterial: function () {
            if (this.materials.length > 0) return this.materials[this.materials.length - 1]
          },
          _finalize: function (t) {
            const e = this.currentMaterial();
            if (e && -1 === e.groupEnd && (e.groupEnd = this.geometry.vertices.length / 3, e.groupCount = e.groupEnd - e.groupStart, e.inherited = !1), t && this.materials.length > 1)
              for (let t = this.materials.length - 1; t >= 0; t--) this.materials[t].groupCount <= 0 && this.materials.splice(t, 1);
            return t && 0 === this.materials.length && this.materials.push({
              name: "",
              smooth: this.smooth
            }), e
          }
        }, s && s.name && "function" == typeof s.clone) {
        const t = s.clone(0);
        t.inherited = !0, this.object.materials.push(t)
      }
      this.objects.push(this.object)
    },
    finalize: function () {
      this.object && "function" == typeof this.object._finalize && this.object._finalize(!0)
    },
    parseVertexIndex: function (t, e) {
      const s = parseInt(t, 10);
      return 3 * (s >= 0 ? s - 1 : s + e / 3)
    },
    parseNormalIndex: function (t, e) {
      const s = parseInt(t, 10);
      return 3 * (s >= 0 ? s - 1 : s + e / 3)
    },
    parseUVIndex: function (t, e) {
      const s = parseInt(t, 10);
      return 2 * (s >= 0 ? s - 1 : s + e / 2)
    },
    addVertex: function (t, e, s) {
      const i = this.vertices,
        r = this.object.geometry.vertices;
      r.push(i[t + 0], i[t + 1], i[t + 2]), r.push(i[e + 0], i[e + 1], i[e + 2]), r.push(i[s + 0], i[s + 1], i[s + 2])
    },
    addVertexPoint: function (t) {
      const e = this.vertices;
      this.object.geometry.vertices.push(e[t + 0], e[t + 1], e[t + 2])
    },
    addVertexLine: function (t) {
      const e = this.vertices;
      this.object.geometry.vertices.push(e[t + 0], e[t + 1], e[t + 2])
    },
    addNormal: function (t, e, s) {
      const i = this.normals,
        r = this.object.geometry.normals;
      r.push(i[t + 0], i[t + 1], i[t + 2]), r.push(i[e + 0], i[e + 1], i[e + 2]), r.push(i[s + 0], i[s + 1], i[s + 2])
    },
    addFaceNormal: function (t, e, s) {
      const i = this.vertices,
        r = this.object.geometry.normals;
      n.fromArray(i, t), a.fromArray(i, e), l.fromArray(i, s), h.subVectors(l, a), c.subVectors(n, a), h.cross(c), h.normalize(), r.push(h.x, h.y, h.z), r.push(h.x, h.y, h.z), r.push(h.x, h.y, h.z)
    },
    addColor: function (t, e, s) {
      const i = this.colors,
        r = this.object.geometry.colors;
      void 0 !== i[t] && r.push(i[t + 0], i[t + 1], i[t + 2]), void 0 !== i[e] && r.push(i[e + 0], i[e + 1], i[e + 2]), void 0 !== i[s] && r.push(i[s + 0], i[s + 1], i[s + 2])
    },
    addUV: function (t, e, s) {
      const i = this.uvs,
        r = this.object.geometry.uvs;
      r.push(i[t + 0], i[t + 1]), r.push(i[e + 0], i[e + 1]), r.push(i[s + 0], i[s + 1])
    },
    addDefaultUV: function () {
      const t = this.object.geometry.uvs;
      t.push(0, 0), t.push(0, 0), t.push(0, 0)
    },
    addUVLine: function (t) {
      const e = this.uvs;
      this.object.geometry.uvs.push(e[t + 0], e[t + 1])
    },
    addFace: function (t, e, s, i, r, o, n, a, l) {
      const c = this.vertices.length;
      let h = this.parseVertexIndex(t, c),
        p = this.parseVertexIndex(e, c),
        u = this.parseVertexIndex(s, c);
      if (this.addVertex(h, p, u), this.addColor(h, p, u), void 0 !== n && "" !== n) {
        const t = this.normals.length;
        h = this.parseNormalIndex(n, t), p = this.parseNormalIndex(a, t), u = this.parseNormalIndex(l, t), this.addNormal(h, p, u)
      } else this.addFaceNormal(h, p, u);
      if (void 0 !== i && "" !== i) {
        const t = this.uvs.length;
        h = this.parseUVIndex(i, t), p = this.parseUVIndex(r, t), u = this.parseUVIndex(o, t), this.addUV(h, p, u), this.object.geometry.hasUVIndices = !0
      } else this.addDefaultUV()
    },
    addPointGeometry: function (t) {
      this.object.geometry.type = "Points";
      const e = this.vertices.length;
      for (let s = 0, i = t.length; s < i; s++) {
        const i = this.parseVertexIndex(t[s], e);
        this.addVertexPoint(i), this.addColor(i)
      }
    },
    addLineGeometry: function (t, e) {
      this.object.geometry.type = "Line";
      const s = this.vertices.length,
        i = this.uvs.length;
      for (let e = 0, i = t.length; e < i; e++) this.addVertexLine(this.parseVertexIndex(t[e], s));
      for (let t = 0, s = e.length; t < s; t++) this.addUVLine(this.parseUVIndex(e[t], i))
    }
  };
  return t.startObject("", !1), t
}
class u extends t.Loader {
  constructor(t) {
    super(t), this.materials = null
  }
  load(e, s, i, r) {
    const o = this,
      n = new t.FileLoader(this.manager);
    n.setPath(this.path), n.setRequestHeader(this.requestHeader), n.setWithCredentials(this.withCredentials), n.load(e, (function (t) {
      try {
        s(o.parse(t))
      } catch (t) {
        r ? r(t) : console.error(t), o.manager.itemError(e)
      }
    }), i, r)
  }
  setMaterials(t) {
    return this.materials = t, this
  }
  parse(e) {
    const n = new p; - 1 !== e.indexOf("\r\n") && (e = e.replace(/\r\n/g, "\n")), -1 !== e.indexOf("\\\n") && (e = e.replace(/\\\n/g, ""));
    const a = e.split("\n");
    let l = "",
      c = "",
      h = 0,
      u = [];
    const d = "function" == typeof "".trimLeft;
    for (let t = 0, e = a.length; t < e; t++)
      if (l = a[t], l = d ? l.trimLeft() : l.trim(), h = l.length, 0 !== h && (c = l.charAt(0), "#" !== c))
        if ("v" === c) {
          const t = l.split(/\s+/);
          switch (t[0]) {
            case "v":
              n.vertices.push(parseFloat(t[1]), parseFloat(t[2]), parseFloat(t[3])), t.length >= 7 ? n.colors.push(parseFloat(t[4]), parseFloat(t[5]), parseFloat(t[6])) : n.colors.push(void 0, void 0, void 0);
              break;
            case "vn":
              n.normals.push(parseFloat(t[1]), parseFloat(t[2]), parseFloat(t[3]));
              break;
            case "vt":
              n.uvs.push(parseFloat(t[1]), parseFloat(t[2]))
          }
        } else if ("f" === c) {
      const t = l.substr(1).trim().split(/\s+/),
        e = [];
      for (let s = 0, i = t.length; s < i; s++) {
        const i = t[s];
        if (i.length > 0) {
          const t = i.split("/");
          e.push(t)
        }
      }
      const s = e[0];
      for (let t = 1, i = e.length - 1; t < i; t++) {
        const i = e[t],
          r = e[t + 1];
        n.addFace(s[0], i[0], r[0], s[1], i[1], r[1], s[2], i[2], r[2])
      }
    } else if ("l" === c) {
      const t = l.substring(1).trim().split(" ");
      let e = [];
      const s = [];
      if (-1 === l.indexOf("/")) e = t;
      else
        for (let i = 0, r = t.length; i < r; i++) {
          const r = t[i].split("/");
          "" !== r[0] && e.push(r[0]), "" !== r[1] && s.push(r[1])
        }
      n.addLineGeometry(e, s)
    } else if ("p" === c) {
      const t = l.substr(1).trim().split(" ");
      n.addPointGeometry(t)
    } else if (null !== (u = s.exec(l))) {
      const t = (" " + u[0].substr(1).trim()).substr(1);
      n.startObject(t)
    } else if (r.test(l)) n.object.startMaterial(l.substring(7).trim(), n.materialLibraries);
    else if (i.test(l)) n.materialLibraries.push(l.substring(7).trim());
    else if (o.test(l)) console.warn('THREE.OBJLoader: Rendering identifier "usemap" not supported. Textures must be defined in MTL files.');
    else if ("s" === c) {
      if (u = l.split(" "), u.length > 1) {
        const t = u[1].trim().toLowerCase();
        n.object.smooth = "0" !== t && "off" !== t
      } else n.object.smooth = !0;
      const t = n.object.currentMaterial();
      t && (t.smooth = n.object.smooth)
    } else {
      if ("\0" === l) continue;
      console.warn('THREE.OBJLoader: Unexpected line: "' + l + '"')
    }
    n.finalize();
    const m = new t.Group;
    m.materialLibraries = [].concat(n.materialLibraries);
    if (!0 === !(1 === n.objects.length && 0 === n.objects[0].geometry.vertices.length))
      for (let e = 0, s = n.objects.length; e < s; e++) {
        const s = n.objects[e],
          i = s.geometry,
          r = s.materials,
          o = "Line" === i.type,
          a = "Points" === i.type;
        let l = !1;
        if (0 === i.vertices.length) continue;
        const c = new t.BufferGeometry;
        c.setAttribute("position", new t.Float32BufferAttribute(i.vertices, 3)), i.normals.length > 0 && c.setAttribute("normal", new t.Float32BufferAttribute(i.normals, 3)), i.colors.length > 0 && (l = !0, c.setAttribute("color", new t.Float32BufferAttribute(i.colors, 3))), !0 === i.hasUVIndices && c.setAttribute("uv", new t.Float32BufferAttribute(i.uvs, 2));
        const h = [];
        for (let e = 0, s = r.length; e < s; e++) {
          const s = r[e],
            i = s.name + "_" + s.smooth + "_" + l;
          let c = n.materials[i];
          if (null !== this.materials)
            if (c = this.materials.create(s.name), !o || !c || c instanceof t.LineBasicMaterial) {
              if (a && c && !(c instanceof t.PointsMaterial)) {
                const e = new t.PointsMaterial({
                  size: 10,
                  sizeAttenuation: !1
                });
                t.Material.prototype.copy.call(e, c), e.color.copy(c.color), e.map = c.map, c = e
              }
            } else {
              const e = new t.LineBasicMaterial;
              t.Material.prototype.copy.call(e, c), e.color.copy(c.color), c = e
            } void 0 === c && (c = o ? new t.LineBasicMaterial : a ? new t.PointsMaterial({
            size: 1,
            sizeAttenuation: !1
          }) : new t.MeshPhongMaterial, c.name = s.name, c.flatShading = !s.smooth, c.vertexColors = l, n.materials[i] = c), h.push(c)
        }
        let p;
        if (h.length > 1) {
          for (let t = 0, e = r.length; t < e; t++) {
            const e = r[t];
            c.addGroup(e.groupStart, e.groupCount, t)
          }
          p = o ? new t.LineSegments(c, h) : a ? new t.Points(c, h) : new t.Mesh(c, h)
        } else p = o ? new t.LineSegments(c, h[0]) : a ? new t.Points(c, h[0]) : new t.Mesh(c, h[0]);
        p.name = s.name, m.add(p)
      } else if (n.vertices.length > 0) {
        const e = new t.PointsMaterial({
            size: 1,
            sizeAttenuation: !1
          }),
          s = new t.BufferGeometry;
        s.setAttribute("position", new t.Float32BufferAttribute(n.vertices, 3)), n.colors.length > 0 && void 0 !== n.colors[0] && (s.setAttribute("color", new t.Float32BufferAttribute(n.colors, 3)), e.vertexColors = !0);
        const i = new t.Points(s, e);
        m.add(i)
      } return m
  }
}
class d extends t.Loader {
  constructor(t) {
    super(t)
  }
  load(e, s, i, r) {
    const o = this,
      n = "" === this.path ? t.LoaderUtils.extractUrlBase(e) : this.path,
      a = new t.FileLoader(this.manager);
    a.setPath(this.path), a.setRequestHeader(this.requestHeader), a.setWithCredentials(this.withCredentials), a.load(e, (function (t) {
      try {
        s(o.parse(t, n))
      } catch (t) {
        r ? r(t) : console.error(t), o.manager.itemError(e)
      }
    }), i, r)
  }
  setMaterialOptions(t) {
    return this.materialOptions = t, this
  }
  parse(t, e) {
    const s = t.split("\n");
    let i = {};
    const r = /\s+/,
      o = {};
    for (let t = 0; t < s.length; t++) {
      let e = s[t];
      if (e = e.trim(), 0 === e.length || "#" === e.charAt(0)) continue;
      const n = e.indexOf(" ");
      let a = n >= 0 ? e.substring(0, n) : e;
      a = a.toLowerCase();
      let l = n >= 0 ? e.substring(n + 1) : "";
      if (l = l.trim(), "newmtl" === a) i = {
        name: l
      }, o[l] = i;
      else if ("ka" === a || "kd" === a || "ks" === a || "ke" === a) {
        const t = l.split(r, 3);
        i[a] = [parseFloat(t[0]), parseFloat(t[1]), parseFloat(t[2])]
      } else i[a] = l
    }
    const n = new m(this.resourcePath || e, this.materialOptions);
    return n.setCrossOrigin(this.crossOrigin), n.setManager(this.manager), n.setMaterials(o), n
  }
}
class m {
  constructor(e = "", s = {}) {
    this.baseUrl = e, this.options = s, this.materialsInfo = {}, this.materials = {}, this.materialsArray = [], this.nameLookup = {}, this.crossOrigin = "anonymous", this.side = void 0 !== this.options.side ? this.options.side : t.FrontSide, this.wrap = void 0 !== this.options.wrap ? this.options.wrap : t.RepeatWrapping
  }
  setCrossOrigin(t) {
    return this.crossOrigin = t, this
  }
  setManager(t) {
    this.manager = t
  }
  setMaterials(t) {
    this.materialsInfo = this.convert(t), this.materials = {}, this.materialsArray = [], this.nameLookup = {}
  }
  convert(t) {
    if (!this.options) return t;
    const e = {};
    for (const s in t) {
      const i = t[s],
        r = {};
      e[s] = r;
      for (const t in i) {
        let e = !0,
          s = i[t];
        const o = t.toLowerCase();
        switch (o) {
          case "kd":
          case "ka":
          case "ks":
            this.options && this.options.normalizeRGB && (s = [s[0] / 255, s[1] / 255, s[2] / 255]), this.options && this.options.ignoreZeroRGBs && 0 === s[0] && 0 === s[1] && 0 === s[2] && (e = !1)
        }
        e && (r[o] = s)
      }
    }
    return e
  }
  preload() {
    for (const t in this.materialsInfo) this.create(t)
  }
  getIndex(t) {
    return this.nameLookup[t]
  }
  getAsArray() {
    let t = 0;
    for (const e in this.materialsInfo) this.materialsArray[t] = this.create(e), this.nameLookup[e] = t, t++;
    return this.materialsArray
  }
  create(t) {
    return void 0 === this.materials[t] && this.createMaterial_(t), this.materials[t]
  }
  createMaterial_(e) {
    const s = this,
      i = this.materialsInfo[e],
      r = {
        name: e,
        side: this.side
      };

    function o(t, e) {
      if (r[t]) return;
      const i = s.getTextureParams(e, r),
        o = s.loadTexture((n = s.baseUrl, "string" != typeof (a = i.url) || "" === a ? "" : /^https?:\/\//i.test(a) ? a : n + a));
      var n, a;
      o.repeat.copy(i.scale), o.offset.copy(i.offset), o.wrapS = s.wrap, o.wrapT = s.wrap, r[t] = o
    }
    for (const e in i) {
      const s = i[e];
      let n;
      if ("" !== s) switch (e.toLowerCase()) {
        case "kd":
          r.color = (new t.Color).fromArray(s);
          break;
        case "ks":
          r.specular = (new t.Color).fromArray(s);
          break;
        case "ke":
          r.emissive = (new t.Color).fromArray(s);
          break;
        case "map_kd":
          o("map", s);
          break;
        case "map_ks":
          o("specularMap", s);
          break;
        case "map_ke":
          o("emissiveMap", s);
          break;
        case "norm":
          o("normalMap", s);
          break;
        case "map_bump":
        case "bump":
          o("bumpMap", s);
          break;
        case "map_d":
          o("alphaMap", s), r.transparent = !0;
          break;
        case "ns":
          r.shininess = parseFloat(s);
          break;
        case "d":
          n = parseFloat(s), n < 1 && (r.opacity = n, r.transparent = !0);
          break;
        case "tr":
          n = parseFloat(s), this.options && this.options.invertTrProperty && (n = 1 - n), n > 0 && (r.opacity = 1 - n, r.transparent = !0)
      }
    }
    return this.materials[e] = new t.MeshPhongMaterial(r), this.materials[e]
  }
  getTextureParams(e, s) {
    const i = {
        scale: new t.Vector2(1, 1),
        offset: new t.Vector2(0, 0)
      },
      r = e.split(/\s+/);
    let o;
    return o = r.indexOf("-bm"), o >= 0 && (s.bumpScale = parseFloat(r[o + 1]), r.splice(o, 2)), o = r.indexOf("-s"), o >= 0 && (i.scale.set(parseFloat(r[o + 1]), parseFloat(r[o + 2])), r.splice(o, 4)), o = r.indexOf("-o"), o >= 0 && (i.offset.set(parseFloat(r[o + 1]), parseFloat(r[o + 2])), r.splice(o, 4)), i.url = r.join(" ").trim(), i
  }
  loadTexture(e, s, i, r, o) {
    const n = void 0 !== this.manager ? this.manager : t.DefaultLoadingManager;
    let a = n.getHandler(e);
    null === a && (a = new t.TextureLoader(n)), a.setCrossOrigin && a.setCrossOrigin(this.crossOrigin);
    const l = a.load(e, i, r, o);
    return void 0 !== s && (l.mapping = s), l
  }
}
Page({
  modelId: "",
  modelSrc: "",
  mtlSrc: "",
  disposing: !1,
  platform: null,
  frameId: -1,
  videoObj: {
    src: ""
  },
  onLoad(t) {
    console.log("模型参数：", t), this.modelId = t.modelId, this.modelSrc = decodeURIComponent(t.modelSrc), this.mtlSrc = this.modelSrc.replace(".obj", ".mtl"), 
    this.videoObj.src = decodeURIComponent(t.videoSrc)
    this.setData({
      'videoObj.src':decodeURIComponent(t.videoSrc)
    })
  },
  async onReady() {
    wx.showLoading({
      mask: !1,
      title: "加载中"
    }), wx.createSelectorQuery().select("#gl").node().exec((async s => {
      const i = s[0].node;
      this.platform = new e.WechatPlatform(i), t.PLATFORM.set(this.platform);
      const r = new t.WebGL1Renderer({
          canvas: i,
          antialias: !0,
          alpha: !0
        }),
        o = new t.PerspectiveCamera(75, i.width / i.height, .1, 1e3),
        n = new t.Scene,
        a = new t.TextureLoader;
      await a.loadAsync("https://techbrood.com/threejs/examples/textures/UV_Grid_Sm.jpg");
      let l = new d;
      const c = await l.loadAsync(this.mtlSrc);
      c.preload();
      const h = new u;
      h.setMaterials(c);
      const p = await h.loadAsync(this.modelSrc);
      n.add(p);
      const m = new e.OrbitControls(o, i);
      m.enableDamping = !0, r.outputEncoding = t.LinearEncoding, n.add(new t.AmbientLight(16777215, .8)), o.add(new t.PointLight(16777215, .8)), r.setSize(i.width, i.height), r.setPixelRatio(2), r.setClearColor(16777215, .6), p.traverse((function (t) {})), p.position.y = 0, o.position.z = 30;
      const f = () => {
        this.disposing || (this.frameId = t.$requestAnimationFrame(f)), m.update(), r.render(n, o)
      };
      f(), wx.hideLoading()
    }))
  },
  onUnload() {
    this.disposing = !0, t.$cancelAnimationFrame(this.frameId), t.PLATFORM.dispose()
  },
  onTX(t) {
    this.platform.dispatchTouchEvent(t)
  },
  onShareAppMessage(){
    let modelSrc = encodeURIComponent(this.modelSrc);
    let videoSrc = encodeURIComponent(this.videoObj.src);
    let path= '/pages/preview/matrix?modelId=' + this.modelId + '&modelSrc=' + modelSrc+'&videoSrc='+videoSrc;
    return {
      title: '真人手办',
      path: path
    }
  }
});